#!/bin/bash
# SPDX-License-Identifier: GPL-2.0
# Copyright (C) 2024 Fewtarius

if [ -f "${HOME}/.SteamFork/options" ]
then
        source ${HOME}/.SteamFork/options
else
        echo "Please configure ${HOME}/.SteamFork/options before using this script."
        exit 1
fi

for KEY in WEB_HOSTS LOG_PATH
do
        if [ -z "${!KEY}" ]
        then
                echo "Export ${KEY} before using this script."
                exit 1
        fi
done

SYNC_SUM=$(curl -sL https://${WEB_HOSTS[0]}/.sync.txt 2>/dev/null)

function fetch_count() {
  HOST="$1"
  DATA="$2"
  if [ -z "${DATA}" ]
  then
    DATA="latest_rel.releasemeta"
  fi
  VAL=$(ssh -q ${HOST} "grep \"${DATA}\" ${LOG_PATH} | awk '{print \$1}' | sort | uniq | wc -l")
  printf "${VAL}"
}

function total_count() {
  DATA=${1}
  if [ -z "${DATA}" ]
  then
    DATA="latest_rel.releasemeta"
  fi
  for HOST in ${WEB_HOSTS[@]}
  do
    ssh -q ${HOST} "grep '${DATA}' ${LOG_PATH} | awk '{print \$1}'"
  done | sort | uniq | wc -l
}

function sync_status() {
  HOST=${1}
  DATA=${2}
  if [ -z "${DATA}" ]
  then
    DATA=".sync.txt"
  fi
  curl -sL https://${HOST}/${DATA} 2>/dev/null
}

for HOST in ${WEB_HOSTS[@]}
do
  OUTPUT="${OUTPUT}## Instance Report For ${HOST#*@}\n"
  METADATA_COUNT=$(fetch_count ${HOST})
  OUTPUT="${OUTPUT}* Metadata Downloads: ${METADATA_COUNT}\n"
  ISO_DOWNLOADS=$(fetch_count ${HOST} "steamfork.*iso")
  OUTPUT="${OUTPUT}* ISO Downloads: ${ISO_DOWNLOADS}\n"
  UPDATE_DOWNLOADS=$(fetch_count ${HOST} "steamfork.*img.zst")
  OUTPUT="${OUTPUT}* Update Downloads: ${UPDATE_DOWNLOADS}\n"
  SYNC_STATUS=$(sync_status ${HOST#*@})
  if [ "${SYNC_STATUS}" = "${SYNC_SUM}" ]
  then
    SYNC_STATUS="OK"
  else
    SYNC_STATUS="OUT OF SYNC"
  fi
  OUTPUT="${OUTPUT}* Sync Status: ${SYNC_STATUS}\n"
done

OUTPUT="${OUTPUT}## Total Unique Download Requests ($(date --date=' 1 days ago' +%m/%d/%Y))\n"
TOTAL_METADATA=$(total_count "latest_rel.releasemeta")
OUTPUT="${OUTPUT}* Platform Metadata: ${TOTAL_METADATA}\n"
TOTAL_ISOS=$(total_count "steamfork.*iso")
OUTPUT="${OUTPUT}* Installation ISOs: ${TOTAL_ISOS}\n"
TOTAL_UPDATES=$(total_count "steamfork.*img.zst")
OUTPUT="${OUTPUT}* OS Updates: ${TOTAL_UPDATES}\n"

cat <<EOF
${OUTPUT}
EOF

